package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author baisong
 * @date 2025-10-16
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     *
     * @param dto
     */
    @Override
    public void apply(CheckInApplyDto dto)  {
        //校验老人是否已入住
        Elder elder1 = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1));
        if (ObjectUtil.isNotEmpty(elder1)){
            throw new RuntimeException("老人已入住！");
        }
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        //更新床位状态为已入住
        bedMapper.updateApply(bed.getId());
        //新增或更新老人

        Elder  elder2 = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 0));

        Elder elder0 = BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);

        elder0.setStatus(1);
        elder0.setBedId(bed.getId());
        elder0.setBedNumber(bed.getBedNumber());
        if (elder2!=null){
            elder0.setId(elder2.getId());
            elderMapper.updateElder(elder0);
        }else {
            elderMapper.insert(elder0);
        }

        //新增签约办理
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        contract.setElderId(Math.toIntExact(elder0.getId()));
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contract.setElderName(elder0.getName());
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        contract.setStatus(LocalDateTime.now().isAfter(contract.getStartDate())?1:0);
        contractMapper.insert(contract);
        //新增入住信息
        CheckIn checkIn = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderName(elder0.getName());
        checkIn.setElderId(elder0.getId());
        checkIn.setIdCardNo(elder0.getIdCardNo());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);


        //新增入住配置
        CheckInConfig checkInConfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());

        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo applyInfo(Integer id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        CheckIn checkIn = checkInMapper.selectById(id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, id));
        Elder elder = elderMapper.selectById(checkIn.getElderId());

        List<ElderFamilyVo> elderFamilyVos =   JSON.parseArray((checkIn.getRemark()),ElderFamilyVo.class);
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, elder.getId()));
        CheckInElderVo bean1 = BeanUtil.toBean(elder, CheckInElderVo.class);
        String birthday = elder.getBirthday();
        LocalDate ldt = LocalDate.parse(birthday, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        bean1.setAge(LocalDate.now().getYear()-ldt.getYear());
        CheckInConfigVo bean = BeanUtil.toBean(checkIn, CheckInConfigVo.class);
        BeanUtil.copyProperties(checkInConfig,bean);
        checkInDetailVo.setCheckInConfigVo(bean);
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setCheckInElderVo(bean1);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVos);


        return checkInDetailVo;
    }
}
